<?php

/**
 * Created by PhpStorm.
 * User: Celebration-Grey
 * Date: 2017/4/16
 * Time: 14:46
 */
namespace App\Http\Controllers\User;
use App\Http\Classes\Background;
use App\Http\Classes\BackgroundOriginal;
use App\Http\Classes\Common;
use App\Http\Classes\Cover;
use App\Http\Classes\HeadOriginal;
use App\Http\Classes\Head;
use App\Http\Classes\IM\IM;
use App\Http\Classes\Log;
use App\Http\Classes\CoverOriginal;
use App\Http\Classes\RedisCache;
use App\Http\Classes\User;
use App\Http\Controllers\Controller;
use App\Http\Classes\Email;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class UserController extends Controller
{
    public function sessionStart(){
        if(!isset($_COOKIE['php_session_id'])){
            $php_session_id = Common::getSessionId();
            return $this->response(200,"会话已开启",$php_session_id);
        }
        else{
            return $this->response(200,"会话已开启",$_COOKIE['php_session_id']);
        }
    }

    public function login(Request $request){
        if($_POST)
        {
            try
            {
                $mutipledata['email'] = $request->input('user_email');
                $mutipledata['password'] = $request->input('user_password');
                if(User::isEmail($mutipledata['email'])
                    && User::isPassword($mutipledata['password'])) {
                    $result = User::passwordVerifiy($mutipledata['email'],$mutipledata['password']);
                    if($result === null)
                    {
                        return $this->response(304,"账号和密码不匹配，我们无法放你进去！",null);
                    }
                    else
                    {
                        $IM = new IM();
                        $data = array();
                        $data['token'] = $result['token'];
                        $data['accid'] = $result['info']->user_id;
//                        $data['name'] = $result['info']->user_nickname;
//                        $data['icon'] = $result['info']->user_head_img;
                        $response = [];
                        $response['info'] = $result['info'];
//                        $response['info'] = (array)($response['info']);
//                        array_push($response['info'],array('user_token' => $result['token']));

                        $response['token'] = $result['token'];
//                        $response['IM_response'] = json_decode($IM -> update($data));
//                        if($response['IM_response'] -> code === 414 && strstr($response['IM_response'] -> desc,'not register')){
//                            $response['IM_response'] = json_decode($IM -> register($data));
//                        }
                        session(['user_info' => $response]);
                        RedisCache::setUserInfo($result['info']->user_id,$response);
//                        Redis::set('u'.$result['info']->user_id,json_encode($response));
//                        Redis::expire('u'.$result['info']->user_id,60*60*24*7);
                        $IM -> update($data);
                        //echo 1;
                        return $this->response(200,"登录成功，即将进入新世界！",$response);
                    }
                }
                else
                {
                    return $this->response(304,"不要输入一些奇怪的东西给我，我看不懂！",null);
                }
            }
            catch (\Exception $exception)
            {
                Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
                return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
            }
        }
        else
        {
            return $this->response(503,"不要做些奇怪的事情啊喂！如果不是故意的话，刷新页面试试吧！",null);
        }
    }

    public function register(Request $request){
        if($_POST)
        {
            try{
                if($request->has('user_nickname')
                    && $request->has('user_password')
                    && $request->has('re_password')
                    && $request->has('user_email')
                    && $request->has('php_session_id')
                    && $request->has('code')
                    && isset($_COOKIE['php_session_id'])
                    && ($_COOKIE['php_session_id'] == $request->input('php_session_id'))

                ){
                    $data = [];
                    $data['php_session_id'] = $request->input('php_session_id');
                    $data['user_password'] = $request->input('user_password');
                    $data['re_password'] = $request->input('re_password');
                    $data['user_nickname'] = $request->input('user_nickname');
                    $data['user_email'] = $request->input('user_email');
                    $data['code'] = $request->input('code');
                    if(User::isPassword($data['user_password']))
                    {
                        if($data['user_password'] == $data['re_password'])
//                        if(true)
                        {
                            if(User::isNickName($data['user_nickname']))
                            {
                                if(!User::isNicknameExist($data['user_nickname']))
                                {
                                    if(Email::verificate($data['php_session_id'],$data['code'],$data['user_email']))
//                                    if(true)
                                    {
                                        $result = User::insert($data);
                                        if($result)
                                        {
                                            $data = array();
                                            $data['accid'] = $result['user_id'];
                                            $data['token'] = $result['user_token'];
                                            $data['name'] = $result['user_nickname'];
                                            $data['icon'] = $result['user_head_img'];
                                            $IM = new IM();
                                            $response = array();
                                            $response['result'] = $result;
                                            $response['IM_response'] = json_decode($IM->register($data));
                                            return $this->response(200,"恭喜您！完成了艰难的注册过程！",$response);
                                        }
                                        else
                                        {
                                            return $this->response(500,"未知错误！注册失败！",$result);
                                        }
                                    }else
                                    {
                                        return $this->response(304,"口令对不上！应该是过期了吧，刷新重来试试吧！",$data['code']);
                                    }
                                }
                                else
                                {
                                    return $this->response(304,"英雄所见略同！但是大家只会记住一个人！",$data['user_nickname']);
                                }
                            }
                            else
                            {
                                return $this->response(304,"不要用些奇怪的名字啊喂！",$data['user_nickname']);
                            }
                        }
                        else
                        {
                            return $this->response(304,"你为什么会有两个不同的秘密？",null);
                        }
                    }
                    else
                    {
                        return $this->response(304,"用些奇怪的密码，你自己记得住吗？",null);
                    }
                }
                else
                {
                    return $this->response(304,"你少了某样的东西啊喂！",null);
                }
            }
            catch (\Exception $exception)
            {
                Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
                return $this->response(500,'系统内部错误！'.$exception->getMessage(),null);
            }
        }else
        {
            return $this->response(503,"不要做些奇怪的事情啊喂！如果不是故意的话，刷新页面试试吧！",null);
        }
    }

    public function registerRequest(Request $request){
        if($_POST){
            try{
                if($request->has('email') && isset($_COOKIE['php_session_id']))
                {
                    $email = $request->input('email');
                    $php_session_id = $_COOKIE['php_session_id'];
                    if(User::isEmail($email))
                    {
                        if(!User::isEmailExist($email))
                        {
                            $flag = Email::registerEmail($php_session_id,$email);
                            if($flag)
                            {
                                return $this->response(200,"邮件发送成功",null);
                            }
                            else
                            {
                                return $this->response(304,"邮件发送失败",$flag);
                            }
                        }
                        else
                        {
                            return $this->response(304,"邮箱已存在",$email);
                        }
                    }
                    else
                    {
                        return $this->response(304,"邮箱格式不正确",$email);
                    }
                }
                else
                {
                    return $this->response(503,"缺少必要参数",null);
                }
            }
            catch (\Exception $exception)
            {
                Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
                return $this->response(500,'系统内部错误！'.$exception->getMessage(),null);
            }
        }
        else
        {
            return $this->response(503,"不要做些奇怪的事情啊喂！如果不是故意的话，刷新页面试试吧！",null);
        }
    }

    public function cookieLogin(){
        try
        {
            if(isset($_COOKIE['user_token']))
            {
                $user_token = $_COOKIE['user_token'];
                $user_id = $_COOKIE['user_id'];
                $info = User::redisTokenVerifiy($user_id,$user_token);
                if($info)
                {
//                    $data = array();
                    //var_dump($info);
//                    $data['accid'] = $info->user_email;
//                    $data['name'] = $info->user_nickname;
//                    $data['token'] = $user_token;
//                    $data['icon'] = $info->user_head_img;
//                    $IM = new IM();
                    //$response = [];
//                    $response['IM_response'] = json_decode($IM->register($data));
                    //$response['info'] = $info;
                    session(['user_info' => $info]);
                    return $this->response(200,"身边验证成功！",$info);
                }
                else{
                    $info = User::mysqlTokenVerifiy($user_id,$user_token);
                    if($info){
                        session(['user_info' => $info]);
                        return $this->response(200,"身边验证成功！",$info);
                    }
                    else{
                        return $this->response(304,"身边验证失败！",$info);
                    }
                }
            }
            else
            {
                return $this->response(302,"令牌已过期！",null);
            }
        }
        catch (\Exception $exception)
        {
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,'系统内部错误！'.$exception->getMessage(),null);
        }
    }

    public function getResetCode(Request $request){
        if($_POST)
        {
            try
            {
                if(isset($_COOKIE['php_session_id']) && $request->has('user_email'))
                {
                    $data = [];
                    $data['email'] = $request->input('user_email');
                    $data['php_session_id'] = $_COOKIE['php_session_id'];
                    if(User::isEmail($data['email']))
                    {
                        if(User::isEmailExist($data['email']))
                        {
                            $flag = Email::resetEmail($data['php_session_id'],$data['email']);
                            if($flag)
                            {
                                return $this->response(200, "邮件发送成功，请注意您的垃圾箱Orz", null);
                            }
                            else
                            {
                                return $this->response(304, "邮件发送失败！", $flag);
                            }
                        }
                        else{
                            return $this->response(304,"这个邮箱根本不存在!",$data['email']);
                        }
                    }
                    else{
                        return $this->response(304,"这真的是邮箱吗？",$data['email']);
                    }
                }
                else{
                    return $this->response(304,"页面过期啦！请刷新页面",null);
                }
            }
            catch (\Exception $exception)
            {
                Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
                return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
            }
        }
        else
        {
            return $this->response(503,"不听不听，王八念经",null);
        }
    }

    public function resetPassword(Request $request){
        if($_POST)
        {
            try{
                if(isset($_COOKIE['php_session_id'])
                    && $request->has('user_email')
                    && $request->has('user_password')
                    && $request->has('code')
                ){
                    $data = [];
                    $data['email'] = $request->input('user_email');
                    $data['password'] = $request->input('user_password');
                    $data['code'] = $request->input('code');
                    $data['php_session_id'] = $_COOKIE['php_session_id'];
                    if(User::isPassword($data['password'])){
                        $data['code'] = hash('md5',$data['code']);
                        $flag = Email::resetVerifiy($data);
                        if($flag){
                            $result = User::updatePassword($data['email'],$data['password']);
                            if($result){
                                Email::resetDelete($data['email']);
                                return $this->response(200,"重置密码成功！恭喜回来！",null);
                            }
                            else{
                                return $this->response(304,"未知错误！",$result);
                            }
                        }
                        else{
                            return $this->response(304,"验证码有误，或者你变动了某些内容！",null);
                        }
                    }
                    else{
                        return $this->response(304,"你是觉得你忘掉的密码不够难吗？",$data);
                    }
                }
                else{
                    return $this->response(304,"缺少参数或者页面过期啦！请刷新页面",null);
                }
            }
            catch (\Exception $exception){
                Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
                return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
            }
        }
        else
        {
            return $this->response(503,"不听不听，王八念经",null);
        }
    }

    public function logOut(){
        try{
            if(User::logOut()){
                return $this->response(200, '登出成功！',null);
            }
            else{
                return $this->response(304, '退出失败！',null);
            }
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    public function uploadHeadImg(Request $request){
        try{
            $dataArray = $request->all();
            if (isset($dataArray['avatar_name'])
                && isset($dataArray['avatar_src'])
                && isset($dataArray['avatar_type'])
                && isset($dataArray['avatar_data'])){
                $crop = new Head($dataArray['avatar_name'],$dataArray['avatar_src'],$dataArray['avatar_type'],$dataArray['avatar_data']);
                $data = $crop -> getResult();
                $msg = $crop -> getMsg();
                $code = $crop -> getCode();
                return $this->response($code,$msg,$data);
            } else{
                return $this->response(304,'缺少参数！',null);
            }
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    public function uploadCoverImg(Request $request){
        try{
            $dataArray = $request->all();
            if (isset($dataArray['avatar_name'])
                && isset($dataArray['avatar_src'])
                && isset($dataArray['avatar_type'])
                && isset($dataArray['avatar_data'])){
                $crop = new Cover($dataArray['avatar_name'],$dataArray['avatar_src'],$dataArray['avatar_type'],$dataArray['avatar_data']);
                $data = $crop -> getResult();
                $msg = $crop -> getMsg();
                $code = $crop -> getCode();
                return $this->response($code,$msg,$data);
            } else{
                return $this->response(304,'缺少参数！',null);
            }
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    public function uploadBackgroundImg(Request $request){
        try{
            $dataArray = $request->all();
            if (isset($dataArray['avatar_name'])
                && isset($dataArray['avatar_src'])
                && isset($dataArray['avatar_type'])
                && isset($dataArray['avatar_data'])){
                $crop = new Background($dataArray['avatar_name'],$dataArray['avatar_src'],$dataArray['avatar_type'],$dataArray['avatar_data']);
                $data = $crop -> getResult();
                $msg = $crop -> getMsg();
                $code = $crop -> getCode();
                return $this->response($code,$msg,$data);
            } else{
                return $this->response(304,'缺少参数！',null);
            }
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    public function uploadHeadOriginal(){
        try{
            $original = new HeadOriginal($_FILES['avatar_file']);
            $data = $original -> getResult();
            $msg = $original -> getMsg();
            $code = $original -> getCode();
            return $this->response($code,$msg,$data);
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    public function uploadCoverOriginal(){
        try{
            $original = new CoverOriginal($_FILES['avatar_file']);
            $data = $original -> getResult();
            $msg = $original -> getMsg();
            $code = $original -> getCode();
            return $this->response($code,$msg,$data);
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    public function uploadBackgroundOriginal(){
        try{
            $original = new BackgroundOriginal($_FILES['avatar_file']);
            $data = $original -> getResult();
            $msg = $original -> getMsg();
            $code = $original -> getCode();
            return $this->response($code,$msg,$data);
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    public function getSelfInfo(){
        try{
            $user_id = $_COOKIE['user_id'];
            $user = new User($user_id);
            $user = $user ->getSelfInfo();
            if($user){
                return $this->response(200,'获取成功！',$user);
            }
            else{
                return $this->response(304,'获取失败！',null);
            }
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    public function updateSelfInfo(Request $request){
        try{
            $data = $request->all();
            //var_dump($data);
            if(isset($data['user_id']) && $data['user_id'] == $_COOKIE['user_id']){
                $user = new User($_COOKIE['user_id']);
                $user = $user->updateSelfInfo($data);
                if($user == false){
                    return $this->response(304,'修改失败！可能缺少参数或参数不规范',false);
                }
                else if($user == null){
                    return $this->response(304,'修改成功！获取返回信息失败',null);
                }
                else{
                    return $this->response(200,'修改获取成功！',$user);
                }
            }
            else{
                return $this->response(304,'缺少参数！',null);
            }
        }
        catch (\Exception $exception){
            Log::userError(__FUNCTION__,$exception->getCode(),$exception->getMessage(),$exception->getFile(),$exception->getLine(),isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0);
            return $this->response(500,"系统内部错误！".$exception->getMessage(),null);
        }
    }

    private function response($status,$message,$data){
        $response = [];
        $response['status'] = $status;
        $response['message'] = $message;
        $response['data'] = $data;
        return response()->json($response);
    }
}